<?php
/**
 * Print current date or transform existing date.
 *
 * If setted symbol '-' than not transformate date.
 *
 * @link http://ua2.php.net/manual/en/function.date.php
 * @author Anton Danilchenko <anton.danilchenko@gmail.com>
 */
class Templum_Helper_Date implements Templum_Helper_Interface {
	private $_aDateTimeFormat = array(
		// date
		'YYYY'	=> 'Y',	// 2009 (year)
		'YY'	=> 'y',	// 09 (year)
		'MONTH'	=> 'F',	// February (month)
		'MON'	=> 'M',	// Feb (month)
		'MM'	=> 'm',	// 02 (month)
		'M'		=> 'n',	// 2 (month)
		'DAY'	=> 'l',	// Sunday (day)
		'DD'	=> 'd',	// 05 (day)
		'D'		=> 'j',	// 5 (day)
		// time
		'HH'	=> 'H',	// 08 (hours)
		'H'		=> 'G',	// 8 (hours)
		'II'	=> 'i',	// 03 (minutes)
		'I'		=> 'i',	// 03 (minutes)
		'SS'	=> 's',	// 04 (seconds)
		'S'		=> 's');// 04 (seconds)


	/**
	 * Return result of current helper.
	 *
	 * @param string $sData: processing string
	 * @param array $aParams: 0 - date (timestamp or mysql date|datetime)
	 */
	public function handle(&$sData, $aParams=array()) {
		// not execute if set special symbol
		if ('-'==$sData)
			return;
		// get parameters
		$sFormat = isset($aParams[0]) ? $aParams[0] : 'YYYY-MM-DD HH:MM:SS';
		// date in timestamp format
		$iTimestamp = isset($sData) ? $sData : time();
		// existing date
		if (! is_numeric($iTimestamp))
			$iTimestamp = $this->_getDatetimeToTimestamp($iTimestamp);
		// translate format string
		$sFormat = str_replace(array_keys($this->_aDateTimeFormat), array_values($this->_aDateTimeFormat), $sFormat);
		// translate date and save result
		$sData = date($sFormat, $iTimestamp);
	}


	/**
	 * Transform mysql date or datetime to timestamp format.
	 *
	 * Handle date and datetime formats:
	 *  - full form ("YYYY-MM-DD HH:MM:SS", "YYYY/MM/DD HH-MM-SS", "YYYY:MM:DD HH-MM-SS", ...)
	 *  - short form ("YYYY-MM-DD", "YYYY/MM/DD", ...)
	 *
	 * @return int: timestamp
	 */
	private function _getDatetimeToTimestamp($sDatetime) {
		// parse data string
		$aDatetimeInfo = split('[ ./:-]', $sDatetime);
		// set all not setted information
		for ($iNum=0; $iNum<=5; $iNum++)
			if (empty($aDatetimeInfo[$iNum]))
				$aDatetimeInfo[$iNum] = 0;
		// return timestamp
		return mktime($aDatetimeInfo[3], $aDatetimeInfo[4], $aDatetimeInfo[5], $aDatetimeInfo[1], $aDatetimeInfo[2], $aDatetimeInfo[0]);
	}
}